package com.haibara.codesubmiteval.chain.redisRunnerChain;

import cn.hutool.json.JSONUtil;
import com.haibara.codesubmiteval.constant.AuthConstant;
import com.haibara.codesubmiteval.constant.RedisKeyConstant;
import com.haibara.codesubmiteval.model.entity.User;
import com.haibara.codesubmiteval.model.vo.Top10VO;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * Top10榜单
 *
 * @Author: mengyu
 * @Date: 2025/4/29
 */
@Order(3)
@Component
@Slf4j
public class Top10InitHandler extends RedisInitHandler {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void handleRedisInit(RedisInitContext context) {
        for (User user : context.getUsers()) {
            // 管理员不参与Top10
            if (Objects.equals(user.getUserRole(), AuthConstant.USER)) {
                stringRedisTemplate.opsForZSet().add(
                        RedisKeyConstant.top10,  //key
                        JSONUtil.toJsonStr(
                                Top10VO.builder()
                                        .userId(user.getId())
                                        .build()
                        )  //value
                        ,
                        user.getScore()  //score
                );
            }
        }
        log.info("RedisInit - Top10完成");
        if (next != null) next.handleRedisInit(context);
    }
}
